package com.zl.payment.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zl.payment.entity.*;
import com.zl.payment.service.*;
import com.zl.payment.util.DateUtils;
import com.zl.payment.util.PaymentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;


import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 黄军鹏
 * @since 2020-07-15
 */
@Controller
@RequestMapping("/payment/month-bill")
public class MonthBillController {
    @Autowired
    private IMonthBillService monthBillService;
    @Autowired
    private IRepaymentRecordService repaymentRecordService;
    @Autowired
    private IInstallmentRateService installmentRateService;
    @Autowired
    private IInstallmentRecordService installmentRecordService;
    @Autowired
    private IInstallmentBillService installmentBillService;
    @Autowired
    private IHistoryBillService historyBillService;
    @GetMapping("show/{creditCardId}")
    public String showMonthBill(@PathVariable("creditCardId") String creditCardId, Model model){
        MonthBill monthBill = monthBillService.getMonthBill(creditCardId);
        BigDecimal totalAmount = monthBillService.getTotalAmount(monthBill);
        Date date = monthBill.getBillDate();
        Date finalRepaymentDate = DateUtils.finalRepaymentDate(date);
        model.addAttribute("monthBill",monthBill);
        model.addAttribute("totalAmount",totalAmount);
        model.addAttribute("finalRepaymentDate",finalRepaymentDate);
        return "view/showMonthBill";
    }
    
    
    
    @GetMapping("total/{creditCardId}")
    public String totalRepayment(@PathVariable("creditCardId")String creditCardId, Model  model){
        MonthBill monthBill = monthBillService.getMonthBill(creditCardId);
        BigDecimal totalAmount = monthBillService.getTotalAmount(monthBill);
        model.addAttribute("monthBill",monthBill);
        model.addAttribute("totalAmount",totalAmount);
        return "view/totalRepay";
    }
    @PostMapping("totalRepay/{creditCardId}")
    public String totalRepay(@PathVariable("creditCardId")String creditCardId,String cardNo,BigDecimal totalAmount,Model model){
        MonthBill monthBill = monthBillService.getMonthBill(creditCardId);
        String billId = monthBill.getBillId();
        boolean repayment = repaymentRecordService.repayment(creditCardId, billId, PaymentType.全额还款, totalAmount, cardNo);
        UpdateWrapper<MonthBill> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("BILL_ID",monthBill.getBillId());
        updateWrapper.set("BILL_STATUS",1);
        boolean update = monthBillService.update(updateWrapper);
        if (repayment&&update){
         model.addAttribute("message","全额还款成功");
         return "view/repayResult";
        }
        model.addAttribute("message","全额还款失败");
        return "view/repayResult";
    }
    
    @GetMapping("installment/{creditCardId}")
    public String installment(@PathVariable("creditCardId") String creditCardId,Model model) {
        MonthBill monthBill = monthBillService.getMonthBill(creditCardId);
        BigDecimal maxInsatllmentAmount = monthBillService.getInstallmentAmount(monthBill);
        List<InstallmentRate> installmentRates = installmentRateService.list(null);
        model.addAttribute("maxInsatllmentAmount",maxInsatllmentAmount);
        model.addAttribute("installmentRates",installmentRates);
        return "view/installment";
    }
    @PostMapping("installment/{creditCardId}")
    public String installment(@PathVariable("creditCardId") String creditCardId, BigDecimal installmentAmount, Integer insatllmentNum,Model model){
        MonthBill monthBill = monthBillService.getMonthBill(creditCardId);
        BigDecimal restAmount = monthBillService.restAmount(monthBill, installmentAmount);
        BigDecimal rate = installmentRateService.getOne(new QueryWrapper<InstallmentRate>().eq("BILL_NUMBERS", insatllmentNum)).getBillRate();
        BigDecimal monthRate = installmentAmount.multiply(rate).divide(new BigDecimal("100"));
        model.addAttribute("restAmount",restAmount);
        model.addAttribute("installmentAmount",installmentAmount);
        model.addAttribute("insatllmentNum",insatllmentNum);
        model.addAttribute("rate",rate);
        model.addAttribute("monthRate",monthRate);
        return "installmentRepay";
        
    }
    
    @PostMapping("installmentRepay/{creditCardId}")
    public String installmentRepay(@PathVariable("creditCardId")  String creditCardId,BigDecimal installmentAmount,
                                   BigDecimal restAmount,Integer insatllmentNum,BigDecimal monthRate,String cardNo,Model model){
        //查到月账单
        MonthBill monthBill = monthBillService.getMonthBill(creditCardId);
        //增加还款记录
        boolean repayment = repaymentRecordService.repayment(creditCardId, monthBill.getBillId(), PaymentType.分期还款, restAmount, cardNo);
        //添加分期记录
        String recordId = UUID.randomUUID().toString().replaceAll("-","").substring(0,15);
        InstallmentRecord installmentRecord = new InstallmentRecord(recordId, creditCardId, monthBill.getBillId(), monthBillService.getTotalAmount(monthBill)
                , installmentAmount, insatllmentNum, DateUtils.today(), DateUtils.billMonth());
        boolean  record = installmentRecordService.save(installmentRecord);
        //添加分期账单
        BigDecimal monthAmount = installmentAmount.divide(new BigDecimal(insatllmentNum + ""),2, RoundingMode.UP);//每月应还的金额
        String[] months = DateUtils.getMonths(insatllmentNum);
        ArrayList<InstallmentBill> installmentBills = new ArrayList<>();
        for (int i = 1; i <= insatllmentNum; i++) {
            String billId = UUID.randomUUID().toString().replaceAll("-","").substring(0,15);
            installmentBills.add(new InstallmentBill(billId,creditCardId,recordId,insatllmentNum,i,months[i-1],monthAmount,monthRate,0));
        }
        System.out.println(installmentBills);
        boolean saveBatch = installmentBillService.saveBatch(installmentBills);
        //更改月账单状态
        UpdateWrapper<MonthBill> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("BILL_ID",monthBill.getBillId());
        updateWrapper.set("BILL_STATUS",2);
        boolean update = monthBillService.update(updateWrapper);
        if (repayment&&record&&saveBatch&&update){
            model.addAttribute("message","账单分期还款成功");
            return "view/repayResult";
        }
        model.addAttribute("message","账单分期还款失败");
        return "view/repayResult";
    }
    @GetMapping("partial/{creditCardId}")//部分还款   部分还款页面
    public String partial(@PathVariable ("creditCardId") String creditCardId,Model model){
        MonthBill monthBill = monthBillService.getMonthBill(creditCardId);
        BigDecimal leastAmont = monthBillService.leastAmont(monthBill);
        model.addAttribute("leastAmont",leastAmont);
        return "partial";
    }
    @PostMapping("partialPayment/{creditCardId}")
    public String partialRepay(@PathVariable ("creditCardId") String creditCardId,BigDecimal actuallyAmount,String cardNo,Model model){
        //获取账单
        MonthBill monthBill = monthBillService.getMonthBill(creditCardId);
        
        BigDecimal totalSimpleAmount = monthBill.getConsumSimpleAmount().add(monthBill.getHistoryAmount()).add(monthBill.getHistoryInterest());
        BigDecimal totalInstallAmount = monthBill.getConsumInstallmentAmount().add(monthBill.getHistoryAmount()).add(monthBill.getHistoryInterest());
        BigDecimal remainAmount = totalSimpleAmount.add(totalInstallAmount).subtract(actuallyAmount);
        //需要计算利息的金额
        BigDecimal interest = totalSimpleAmount.multiply(new BigDecimal("0.0005")).multiply(new BigDecimal("30"));//初始利息 消费金额*0.0005*记账日到第一次还款的天数 这里比较复杂暂定为30
        //添加还款记录
        boolean repayment = repaymentRecordService.repayment(creditCardId, monthBill.getBillId(), PaymentType.自选额度还款, actuallyAmount, cardNo);
        //更新历史账单
        HistoryBill historyBill = historyBillService.getHistoryBill(creditCardId);
        historyBill.setUpdateTime(DateUtils.today()).setSimpleBillAmount(totalSimpleAmount).setInstallmentBillAmount(totalInstallAmount)
        .setPaidAmount(actuallyAmount).setRemainingBillAmount(remainAmount).setInitialInterest(interest);
        boolean update = historyBillService.updateById(historyBill);
        //更改月账单
        monthBill.setBillStatus(3);
        boolean update1 = monthBillService.updateById(monthBill);
        if (repayment&&update&&update1){
            model.addAttribute("message","部分还款成功");
            return "view/repayResult";
        }
        model.addAttribute("message","部分还款失败");
        return "view/repayResult";
    
    
    }
}
